package com.oa.tools.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.oa.tools.dao.OAFlowInstanceDAO;
import com.oa.tools.dao.PersonDAO;
import com.oa.tools.entity.OAFlowInstanceWithBLOBs;
import com.oa.tools.jobs.DynamicJob;
import com.oa.tools.jobs.FlowHandlerTaskBase;
import com.oa.tools.utils.DateUtil;
import com.oa.tools.utils.ExceptionUtil;
import com.oa.tools.utils.MailUtil;
import com.oa.tools.utils.ObjectUtil;
import com.oa.tools.utils.StringUtil;
import com.oa.tools.utils.SysConfig;
import com.oa.tools.utils.http.OKHttpClientUtil;


@RestController
public class OAToolsController {

	@Autowired
	DynamicJob myJob;

	@Autowired
	OAFlowInstanceDAO oAFlowInstanceDAO;
	
	@Autowired
	PersonDAO personDAO;
	
	public static final Logger logger = LoggerFactory.getLogger(OAToolsController.class);
	
	@RequestMapping({ "/hello" })
	public ModelAndView hello(String fd_id) throws Exception {
			ModelAndView mv = new ModelAndView("home");
			mv.addObject("lastMilli",DateUtil.date2Str(new Date(this.myJob.getLastestDateMill())));
			mv.addObject("cronStr",this.myJob.getCronStr());
			return mv;
	}
	
	@RequestMapping({ "/email/dept/list" })
	public String email_dept(String fd_id) throws Exception {
		String res = MailUtil.getEmailDeptList().replace("<", "&lt;").replace(">", "&gt;");
		return "<pre>" + StringUtil.prettifyJsonStr(res) + "</pre>";
	}
	
	@RequestMapping({ "/config" })
	public ModelAndView config() throws Exception {
		
		List<String> textList = SysConfig.confText;
		StringBuilder sb = new StringBuilder();
		for(String line:textList) {
			sb.append(line);
			sb.append("\r\n");
		}
		
		ModelAndView mv = new ModelAndView("config");
		mv.addObject("confText",sb.toString());
		
		return mv;
	}
	
	@RequestMapping({ "/config/update" })
	public String config_update(String confText) throws Exception {
		try {
			if(!StringUtil.isBlank(confText)) {
				SysConfig.setConfText(confText);
				this.myJob.update(SysConfig.getSysString("定时表达式"));
				ModelAndView mv = new ModelAndView("config");
				mv.addObject("confText",confText);
				return "提交成功";
			}
				
		}catch(Exception e) {
			return ExceptionUtil.getStackTrace(e);
		}
		
		return "不能提交空数据";
	}
	
	@RequestMapping({ "/email/{user}" })
	public ModelAndView queryEmail(@PathVariable(name="user") String user) throws Exception {
		String email=user+"@fengbangleasing.com";
		String res = MailUtil.getEmailUserInfo(email);
		res = StringUtil.prettifyJsonStr(res);
		
		ModelAndView mv = new ModelAndView("email");
		mv.addObject("userinfo",res);
		return mv;
	}
	
	@RequestMapping({ "/email/update" })
	public String email_update(String userinfo) throws Exception {
		
		Map<String, Object> usermap = ObjectUtil.json2Map(userinfo);
		String res = OKHttpClientUtil.updateEmail(usermap);
		return "返回信息：\r\n"+res;
	}
	
	@RequestMapping({ "/email/list" })
	public String queryAllEmail(String email) throws Exception {
		String res = MailUtil.getAllEmailUserInfo();
		res = StringUtil.prettifyJsonStr(res);
		return "<pre>" + res.replace("<", "&lt;").replace(">", "&gt;") + "</pre>";
	}

	@RequestMapping({ "/create/{fd_id}" })
	public String tryCreate(@PathVariable(name="fd_id") String fd_id) throws Exception {
		OAFlowInstanceWithBLOBs obj = this.oAFlowInstanceDAO.selectByPrimaryKey(fd_id);
		myJob.init();
		FlowHandlerTaskBase p = myJob.getTaskMap().get("AddNewPeopleTask");
		FlowHandlerTaskBase p_wyc = myJob.getTaskMap().get("AddNewWYCPeopleTask");
		FlowHandlerTaskBase p_cyc = myJob.getTaskMap().get("AddNewCYCPeopleTask");
		if(p.startOne(false,false, obj)==null) {
			if (p_wyc.startOne(false,false, obj)==null) {
				return p_cyc.startOne(false,false, obj);
			}
		}
		return null;
	}
	
	@RequestMapping({ "/create/force/{fd_id}" })
	public String forceCreate(@PathVariable(name="fd_id") String fd_id) throws Exception {
		OAFlowInstanceWithBLOBs obj = this.oAFlowInstanceDAO.selectByPrimaryKey(fd_id);
		myJob.init();
		FlowHandlerTaskBase p = myJob.getTaskMap().get("AddNewPeopleTask");
		FlowHandlerTaskBase p_wyc = myJob.getTaskMap().get("AddNewWYCPeopleTask");
		FlowHandlerTaskBase p_cyc = myJob.getTaskMap().get("AddNewCYCPeopleTask");
		if(p.startOne(true,true, obj)==null) {
			if (p_wyc.startOne(true,true, obj)==null) {
				return p_cyc.startOne(true,true, obj);
			}
		}
		return null;
	}

	@RequestMapping({ "/create/list" })
	public String createList() throws Exception {
		myJob.init();
		FlowHandlerTaskBase p = myJob.getTaskMap().get("AddNewPeopleTask");
		FlowHandlerTaskBase p_wyc = myJob.getTaskMap().get("AddNewWYCPeopleTask");
		FlowHandlerTaskBase p_cyc = myJob.getTaskMap().get("AddNewCYCPeopleTask");
		StringBuilder sb = new StringBuilder();
		sb.append(p.start(false,false,System.currentTimeMillis()- 1000L * 60 * 60 * 12));
		sb.append(p_wyc.start(false,false,System.currentTimeMillis()- 1000L * 60 * 60 * 12));
		sb.append(p_cyc.start(false,false,System.currentTimeMillis()- 1000L * 60 * 60 * 12));
		return sb.toString();
	}

	@RequestMapping({ "/stamp/add/{fd_id}" })
	public String addStamp(@PathVariable(name="fd_id") String fd_id) throws Exception {
		OAFlowInstanceWithBLOBs obj = this.oAFlowInstanceDAO.selectByPrimaryKey(fd_id);
		myJob.init();
		FlowHandlerTaskBase p = myJob.getTaskMap().get("AddNewStampTask");
		return p.startOne(true,false,obj);
	}
	
	@RequestMapping({ "/stamp/update/{fd_id}" })
	public String updateStamp(@PathVariable(name="fd_id") String fd_id) throws Exception {
		OAFlowInstanceWithBLOBs obj = this.oAFlowInstanceDAO.selectByPrimaryKey(fd_id);
		myJob.init();
		FlowHandlerTaskBase p = myJob.getTaskMap().get("UpdateStampKeeperTask");
		return p.startOne(true,false, obj);
	}
	
	
	@RequestMapping({ "/test/{fd_id}" })
	public String test(@PathVariable(name="fd_id") String fd_id) throws Exception {
		OAFlowInstanceWithBLOBs obj = this.oAFlowInstanceDAO.selectByPrimaryKey(fd_id);
		myJob.init();
		Map<String,FlowHandlerTaskBase> taskMap = myJob.getTaskMap();
		for(String key:taskMap.keySet()) {
			FlowHandlerTaskBase p = taskMap.get(key);
			if(p.startOne(true,false, obj)!=null) {
				break;
			}
		}
		
		return "done";
	}
	
	@RequestMapping({ "/password/page" })
	public ModelAndView chgPwd(HttpServletRequest request) throws Exception {
		ModelAndView mv = new ModelAndView("password");
		
		mv.addObject("contextPath",request.getContextPath());
		mv.addObject("resultMsg","");
		return mv;
	}
	
	
	
	long lastChg = 0L;
	
	@PostMapping({ "/password/change1" })
	public ModelAndView chgPwdPost(HttpServletRequest request,String email,String mobile) throws Exception {
		
		
		ModelAndView mv = new ModelAndView("password");
		mv.addObject("contextPath",request.getContextPath());
		String resultMsg = "提交过快，请稍后重试";
		if(System.currentTimeMillis()-lastChg<1000) {
			resultMsg = "提交过快，请稍后重试";
		}else {
			lastChg = System.currentTimeMillis();
			if(!email.endsWith("@fengbangleasing.com")) {
				email = (email+"@fengbangleasing.com").replaceAll("\\s", "");
			}
			resultMsg = myJob.chgPass(email, mobile);
		}
		
		mv.addObject("resultMsg",resultMsg);
		return mv;
	}
	
	/*
	 * 解决报错：Refused to execute script from 'http://oa-tool.fengbangleasing.com/password/change?email=sushaolei&mobile=13811070055&callback=callback' 
	 *		because its MIME type ('text/plain') is not executable, and strict MIME type checking is enabled.
	 */
	@RequestMapping( value= "/password/change",produces="text/javascript;charset=UTF-8") 
	@ResponseBody
	public String chgPwdJsonP(HttpServletRequest request,String email,String mobile) throws Exception {
		
		
		ModelAndView mv = new ModelAndView("password");
		mv.addObject("contextPath",request.getContextPath());
		String resultMsg = "提交过快，请稍后重试";
		if(System.currentTimeMillis()-lastChg<1000) {
			resultMsg = "提交过快，请稍后重试";
		}else {
			lastChg = System.currentTimeMillis();
			resultMsg = myJob.chgPass(email, mobile);
		}
		logger.info(email+"-"+mobile+"change pass result:"+resultMsg);
		return "callback('"+resultMsg+"')";
	}
}